/*
 * Copyright (c) 2010 Curtis Boyden.  All rights reserved. 
 * This software was developed by Curtis Boyden and is provided under the terms 
 * of the GNU Lesser General Public License, Version 2.1. You may not use 
 * this file except in compliance with the license. If you need a copy of the license, 
 * please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is ejMud
 * (Ewerp Java MUD).  The Initial Developer is Curtis Boyden.
 *
 * Software distributed under the GNU Lesser Public License is distributed on an "AS IS" 
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or  implied. Please refer to 
 * the license for the specific language governing your rights and limitations.
*/

package com.ewerp.mud.core;

import java.net.ServerSocket;
import java.util.LinkedList;
import java.util.List;

import com.ewerp.mud.communications.ServerSocketHandler;
import com.ewerp.mud.core.exceptions.EwerpMudException;
import com.ewerp.mud.core.plugin.IPlugin;
import com.ewerp.mud.core.session.ISession;
import com.ewerp.mud.core.session.ISessionManager;
import com.ewerp.mud.lifecycle.ILifecycleListener;

public class EwerpSessionManager implements IPlugin, ISessionManager, ILifecycleListener {
    
    protected static EwerpSessionManager instance = new EwerpSessionManager();
    
    protected ServerSocket serverSocket = null;
    
    protected List<ISession> sessions = new LinkedList<ISession>();
    
    protected Thread serverThread = null;
    protected ServerSocketHandler serverSocketHandler = null;
    
    public static EwerpSessionManager getInstance() {
        if(instance == null) {
            instance = new EwerpSessionManager();
        }
        return instance;
    }
    
    protected EwerpSessionManager() {
    }
    
    @Override
	public Class<?>[] getInterfaces() {
		return new Class<?>[] { ISessionManager.class };
	}

    @Override
    public void init() {
    }
    
    @Override
    public void start() {
        try {
            serverSocket = new ServerSocket(5555);
            
            serverSocketHandler = new ServerSocketHandler();
            
            serverSocketHandler.setServerSocket(serverSocket);
            serverSocketHandler.setSessionManager(this);
            
            serverThread = new Thread(serverSocketHandler);
            serverThread.start();
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    @Override
    public void pause() {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void stop() {
        serverSocketHandler.setShutdown(true);
    }

    @Override
    public void registerSession(ISession session) throws EwerpMudException {
        sessions.add(session);
    }

}
